﻿
Imports System.Windows.Forms
Imports osi.input.constants.key_board

Public Class window_key_board_agent
    Inherits agent(Of window_key_board_agent_settings)

    Private ReadOnly control As Control = Nothing
    Private ReadOnly window As Form = Nothing

    Public Sub New(Optional ByVal settings As window_key_board_agent_settings = Nothing)
        MyBase.New(settings)
        control = typed_settings().control
        assert(Not control Is Nothing)
        convertor.cast(Of Form)(control, window)
    End Sub

    Protected Overrides Sub initial()
        MyBase.initial()
        lazy_wait_until(Function() Not control Is Nothing)
        window.KeyPreview() = True
        AddHandler control.PreviewKeyDown, AddressOf preview_key_down
        AddHandler control.KeyDown, AddressOf key_down
        AddHandler control.KeyUp, AddressOf key_up
    End Sub

    Private Sub preview_key_down(ByVal sender As Object, ByVal e As PreviewKeyDownEventArgs)
        If Not e Is Nothing Then
            e.IsInputKey() = True
        End If
    End Sub

    Private Sub key_down(ByVal sender As Object, ByVal e As KeyEventArgs)
        If Not e Is Nothing Then
            assert_begin(add(key_board.case(action.down, e.KeyCode())))
        End If
    End Sub

    Private Sub key_up(ByVal sender As Object, ByVal e As KeyEventArgs)
        If Not e Is Nothing Then
            assert_begin(add(key_board.case(action.press, e.KeyCode()),
                             key_board.case(action.up, e.KeyCode())))
        End If
    End Sub

    Protected Overrides Sub [stop]()
        RemoveHandler control.PreviewKeyDown, AddressOf preview_key_down
        RemoveHandler control.KeyDown, AddressOf key_down
        RemoveHandler control.KeyUp, AddressOf key_up
    End Sub

    Protected Overrides Function rotation_mode() As Boolean
        Return False
    End Function
End Class
